package com.meichaoit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.meichaoit.entity.Account;
import com.meichaoit.util.DBHelp;
import com.meichaoit.util.RowMapper;

public class AccountDao {
	private DBHelp<Account> db =new DBHelp<Account>();
	
	public int save(Account account){
		String sql="insert into t_account(username,password,money,isenable)values(?,?,?,?)";
		return db.executeSQL(sql, account.getUsername(),account.getPassword(),account.getMoney(),account.getIsenable());
	}
	
	public List<Account> findAll(){
		String sql = "SELECT id,username,password,money,isenable FROM t_account ";
		return db.queryForList(sql, new AccountRowMapper());
	}
	
	public class AccountRowMapper implements RowMapper<Account> {

		public Account mapRow(ResultSet rs) throws SQLException {
			Account account = new Account();
			account.setId(rs.getInt("id"));
			account.setIsenable(rs.getInt("isenable"));
			account.setMoney(rs.getFloat("money"));
			account.setPassword(rs.getString("password"));
			account.setUsername(rs.getString("username"));
			return account;
		}
	
	}
	public int update(Account account) {
			String sql = "update t_account set username = ?,password=?,money=?,isenable=? where id = ?";
			return db.executeSQL(sql, account.getUsername(),account.getPassword(),account.getMoney(),account.getIsenable(),account.getId());
		}
	public Account login(String name,String pwd){
		String sql = "SELECT id,username,password,money,isenable FROM t_account WHERE username=? AND password=?";
		return (Account) db.queryForObject(sql, new AccountRowMapper(), name,pwd);
		
	}
	
	public Account findById(int id) {
		String sql = "SELECT id,username,password,money,isenable FROM t_account WHERE id=?";
		return (Account) db.queryForObject(sql, new AccountRowMapper(), id);
	}
}
